<?php
/**
 * 模型相关
 * 
 * @package ews
 * @ews Enterprise WorkShop
 * @version 1.0
 * @since 2011-06-13
 * @author monkee
 */

class modelModel extends model
{
	public function create($user_id, $username, $relate_id, $type, $subject, $message){
		$model_id = DB::insert('model', array(
			'user_id' => $user_id,
			'username' => $username,
			'relate_id' => $relate_id,
			'type' => $type,
			'subject' => $subject,
			'message' => $message
		));
		return $model_id;
	}
	
	public function get_model_id($type, $relate_id){
		$row = DB::fetchOne('SELECT model_id FROM '.DB::table('model').' WHERE type = "'.DB::escape_string($type).'" AND relate_id = '.intval($relate_id));
		return intval($row['model_id']);
	}
	
	public function update_tags($model_id, $tags){
		$a = array();
		foreach(explode(',', $tags) as $i){
			$i = trim($i);
			if(!empty($i)){
				$a[] = $i;
			}
		}
		$tags = implode(',', $a);
		DB::update('model', array('tags' => $tags), 'model_id = '.$model_id);
	}
	/**
	 * 设置model的reply_count加一
	 * 
	 * @param unknown_type $model_id
	 */
	public function set_reply_count_up($model_id){
		$sql = "update ".DB::table('model')." set reply_count=reply_count+1 where model_id=$model_id";
		DB::query($sql);
	}
	public function get_model($model_id){
		return DB::fetchOne('SELECT * FROM '.DB::table('model').' WHERE model_id = '. $model_id);
	}
	
	
	
	//后期需要加权限
	public function get_models_by_user_id($user_id,$pagesize,$pagenum){
		if($pagesize<=0 || $pagenum<=0) return array();
		$row = DB::fetchOne("SELECT count(*) as num FROM ".DB::table('model'));
		$totalcount = $row['num'];
		if($totalcount==0) return array();
		//分页获取
		$totalpage = ceil($totalcount / $pagesize);
		$pagenum = min($totalpage, $pagenum);
		$limitstart = ($pagenum-1)*$pagesize;
		$r = DB::fetchArray("SELECT * FROM ".DB::table('model')." order by model_id desc limit $limitstart,$pagesize");
		return $r;
	}
	public function get_models_count_by_user_id($user_id){
		$row = DB::fetchOne("SELECT count(*) as num FROM ".DB::table('model'));
		return $row['num'];
	}
	
	
	
	
}
?>